package com.anolesoft.twelvePlan.listener;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.twelvePlan.dto.MesPlanJiedianExport;
import com.anolesoft.twelvePlan.entity.MesPlanJiedianDO;
import com.anolesoft.twelvePlan.service.MesPlanJiedianService;
import com.anolesoft.yr.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zyq
 * @date 2022/8/16
 */
@Slf4j
public class MesPlanJiedianListener implements ReadListener<MesPlanJiedianExport> {
    private static final int BATCH_COUNT = 1000;

    private List<MesPlanJiedianExport> list = new ArrayList<>();

    private List<MesPlanJiedianDO> communityList = new ArrayList<>(BATCH_COUNT);

    private MesPlanJiedianService mesPlanJiedianService;

    public MesPlanJiedianListener(MesPlanJiedianService mesPlanJiedianService){
        this.mesPlanJiedianService = mesPlanJiedianService;
    }

    @Override
    public void onException(Exception e, AnalysisContext analysisContext) throws Exception {

    }

    @Override
    public void invokeHead(Map<Integer, CellData> map, AnalysisContext analysisContext) {

    }

    @Override
    public void invoke(MesPlanJiedianExport mesPlanJiedianExport, AnalysisContext analysisContext) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        MesPlanJiedianDO mesPlanJiedianDO = BeanUtil.copyProperties(mesPlanJiedianExport, MesPlanJiedianDO.class);
        mesPlanJiedianDO.setCrerateId(loginUser.getEmpUid());
        mesPlanJiedianDO.setFactoryId(loginUser.getFacCode());
        communityList.add(mesPlanJiedianDO);
        if (communityList.size() >= BATCH_COUNT) {
            batchInsert();
            communityList.clear();
        }
    }

    @Override
    public void extra(CellExtra cellExtra, AnalysisContext analysisContext) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        batchInsert();
    }

    @Override
    public boolean hasNext(AnalysisContext analysisContext) {
        return true;
    }

    void batchInsert(){
        log.debug("数据：{}", communityList);
        mesPlanJiedianService.uploadJiedian(communityList);
    }

}
